package com.dcjt.firehotcarpad.retrofit1.repository;

import android.accounts.AccountsException;
import android.accounts.NetworkErrorException;
import android.app.Activity;
import android.content.DialogInterface;

import com.aries.library.fast.manager.LoggerManager;
import com.aries.library.fast.retrofit.FastTransformer;
import com.aries.library.fast.util.FastStackUtil;
import com.dcjt.firehotcarpad.R;
import com.dcjt.firehotcarpad.entity.BaseEntity;
import com.dcjt.firehotcarpad.retrofit1.exception.EmptyException;
import com.dcjt.firehotcarpad.utils.AlertViewUtil;
import com.dcjt.firehotcarpad.utils.LoginStatusUtils;

import java.util.List;
import java.util.zip.DataFormatException;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;

/**
 * Created: AriesHoo on 2017/11/1 18:17
 * E-Mail: AriesHoo@126.com
 * Function: retrofit使用基类封装.
 * Description:
 */
public abstract class BaseRepository1 {

    /**
     * 只返回实体部分--如查询某个详情信息
     *
     * @param observable
     * @param <T>
     * @return
     */
    protected <T> Observable<T> transform(Observable<List<T>> observable) {
        return transform(observable, false);
    }

    /**
     * @param observable 用于解析 统一返回实体统一做相应的错误码--如登录失效
     * @param <T>
     * @return
     */
    protected <T> Observable<T> transform(Observable<List<T>> observable, boolean isUserInfo) {
        return FastTransformer.switchSchedulers(observable)
                .flatMap(new Function<List<T>, ObservableSource<T>>() {
                    @Override
                    public ObservableSource<T> apply(@NonNull List<T> result) throws Exception {
                        if (result == null) {
                            return Observable.error(new NetworkErrorException());
                        } else if (result.size() == 0) {
                            if (isUserInfo) {
                                LoggerManager.e("数据为空");
                                return Observable.error(new AccountsException());
                            }
                            return Observable.error(new EmptyException("暂无数据"));
                        } else {
                            return Observable.just(result.get(0));
                        }
                    }
                });
    }


    <T> Observable<T> transformer(Observable<BaseEntity<T>> observable) {
        return FastTransformer.switchSchedulers(observable)

                .flatMap(new Function<BaseEntity<T>, Observable<T>>() {
                    @Override
                    public Observable<T> apply(@NonNull BaseEntity<T> result) throws Exception {
                        if (result == null) {
                            return Observable.error(new NetworkErrorException());
                        } else if (result.code == 200 ) {
                            if (result.data == null){
                                return Observable.error(new DataFormatException());
                            }/*else if (result.data instanceof  List){
//                                if (((List) result.data).size() == 0){
//                                    return  Observable.error(new EmptyException("暂无数据"));
//                                }
                            }*/
                            return Observable.just((T) result.data);
                        }else if (result.code == 203 ) {
                            //token失效
                            TokenOld(result.code);
                            return null;
                        }else if (result.code == 206 ) {
                            //重复登录
                            LoginOut(result.code);
                            return null;
                        } else if (result.code == 204 ) {
                            // {"code":204,"msg":"登陆失效"}
                            TokenOld(result.code);
                            return null;
                        } else if (result.data == null) {
                            return Observable.error(new DataFormatException());
                        } else {
                            return Observable.error(new NetworkErrorException());
                        }

                    }
                });
    }

    /**
     * 重复登录
     * @param str
     */
    private void LoginOut(int str) {

        Activity activity = FastStackUtil.getInstance().getCurrent();
        if (activity.getClass().getSimpleName().equals("com.dcjt.firehotcarpad.moudle.LoginActivity")){
            return;
        }

        AlertViewUtil.show(
                activity,
//                str == 206?R.string.cf_login:R.string.token，
               R.string.cf_login,
                R.string.sure,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == DialogInterface.BUTTON_POSITIVE) {
                            LoginStatusUtils.loginOut(activity,false);
                        }
                    }
                }
        );

    }

    /**
     * 登录失效重新登录
     * @param str
     */
    private void TokenOld(int str) {

        Activity activity = FastStackUtil.getInstance().getCurrent();
        if (activity.getClass().getSimpleName().equals("com.dcjt.firehotcarpad.moudle.LoginActivity")){
            return;
        }
        LoginStatusUtils.loginOut(activity,true);
    }

    <T> Observable<T> transformerPmq(Observable<String> observable) {
        return (Observable<T>) FastTransformer.switchSchedulers(observable)

                .flatMap(new Function<String, Observable<String>>() {
                    @Override
                    public Observable<String> apply(@NonNull String result) throws Exception {
                        if (result == null) {
                            return Observable.error(new NetworkErrorException());
                        } else  {
                            return Observable.just(result);
                        }

                    }
                });
    }
}
